const Ws = require('ws');

; (() => {

  const server = new Ws.Server({ port: 8000 });

  const init = () => {
    bindEvent();
  };

  function bindEvent () {
    server.on('open', handleOpen);
    server.on('close', handleClose);
    server.on('error', handleError);
    server.on('connection', handleConnection);
  }

  function handleOpen () {
    console.log('websocket open');
  }

  function handleClose () {
    console.log('websocket close');
  }

  function handleError () {
    console.log('websocket erroe');
  }

  function handleConnection (ws) {
    console.log('websocket connect');
    ws.on('message', handleMessage);
  }

  function handleMessage (msg) {
    var data = msg.toString()
    server.clients.forEach(function (c) {
      c.send(data)
    })
  }

  init();

})();